package com.binguo.api.service;


import com.binguo.common.paymodel.HttpConnectionManager;
import com.binguo.common.paymodel.MD5Util;
import com.binguo.common.paymodel.WXServerPayConfig;
import com.binguo.common.paymodel.WeixinConfig;
import com.binguo.common.util.JsonUtil;
import com.binguo.common.util.PriceUtil;
import com.github.wxpay.sdk.WXPay;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WXServerPayService {

    private static Logger logger = LoggerFactory.getLogger(WXServerPayService.class);

    public static String sub_appid = "wx5433e72fcae4f1e5";//admin@yunpengai.com
    public static String sub_mch_id = "1508590551";
    public static String appSecret = "147107f302f54c94f40010347934d2b1";
    public static String success = "SUCCESS";
    private static final String payUrl = "http://binguoai.com/appapi/wxpay/callback";

    private WXPay wxPay = new WXPay(new WXServerPayConfig());
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");

    private static String client = "yunpeng";
    private static String appid = "C672GHDF56SZXY";

    /**
     * 统一下单
     * @param orderNo
     * @param total_fee
     * @param ip
     * @return
     */
    public String unifiedOrder(String orderNo, Long total_fee, String ip, String sub_appid, String sub_mch_id){
        if (StringUtils.isEmpty(sub_mch_id)) {
            sub_appid = WXServerPayService.sub_appid;
            sub_mch_id = WXServerPayService.sub_mch_id;
        }

        Map<String, String> data = new HashMap<>();

        data.put("body", "商品支付");
        data.put("out_trade_no", orderNo);
        data.put("total_fee", total_fee.toString());
        data.put("spbill_create_ip", ip);
        if (StringUtils.hasText(sub_appid)) {
            data.put("sub_appid", sub_appid);
        }
        data.put("sub_mch_id", sub_mch_id);
        data.put("notify_url", WeixinConfig.getNotifyUrl());
        data.put("trade_type", "NATIVE");

        try {
            Map<String, String> result = wxPay.unifiedOrder(data);

            if (result != null) {
                String return_code = result.get("return_code");
                if (success.equals(return_code)) {
                    String result_code = result.get("result_code");
                    if (success.equals(result_code)) {
                        return result.get("code_url");
                    } else {
                        return "订单失败";
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "订单失败";
    }

    public static void main(String[] args) {

        /*
        Boolean isSuccess = new WXServerPayService().micropayCustomer("kfq121a", "1",
                "180.154.37.230", "135258588378953927", "", "1539085781");

        System.out.println(isSuccess);
        */


        new WXServerPayService().wuzhenpay20("285164176444636187", 1l, "04:92:26:D7:06:42");
    }


    /**
     * 商户直连微信退款
     * @param sub_mch_id 子商户号
     * @param orderNo 订单号
     * @param totalFee 订单总金额
     * @param refundFee 需退款金额
     * @return
     */
    public boolean doWxRefund(String sub_mch_id, String orderNo, String totalFee, String refundFee){
        if (StringUtils.isEmpty(sub_mch_id)) {
            sub_mch_id = WXServerPayService.sub_mch_id;
        }

        Map<String, String> data = new HashMap<>();
        data.put("out_trade_no", orderNo);
        data.put("total_fee", totalFee);
        data.put("refund_fee", refundFee);


        data.put("sub_mch_id", sub_mch_id);
        data.put("out_refund_no", orderNo);
        try {

            logger.info(data.toString());
            Map<String, String> result = wxPay.refund(data);
            logger.info(result.toString());
            if (result != null) {

                String return_code = result.get("return_code");

                logger.info(return_code);

                if (success.equals(return_code)) {
                    String result_code = result.get("result_code");
                    logger.info(result_code);
                    if (success.equals(result_code)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
    /**
     * 提交付款码支付
     * @param orderNo 订单号
     * @param total_fee 总金额 单位为分
     * @param ip 终端ip
     * @param auth_code 用户支付二维码
     *
     * @return 支付结果：true成功  false失败
     */
    public boolean micropayCustomer(String orderNo, String total_fee, String ip, String auth_code, String sub_appid, String sub_mch_id){
        if (StringUtils.isEmpty(sub_mch_id)) {
            sub_appid = WXServerPayService.sub_appid;
            sub_mch_id = WXServerPayService.sub_mch_id;
        }

        Map<String, String> data = new HashMap<>();
        data.put("body", "商品支付");
        data.put("out_trade_no", orderNo);
        data.put("total_fee", total_fee);
        data.put("spbill_create_ip", ip);
        data.put("auth_code", auth_code);

        if (StringUtils.hasText(sub_appid)) {
            data.put("sub_appid", sub_appid);
        }

        data.put("sub_mch_id", sub_mch_id);
        try {

            logger.info(data.toString());
            Map<String, String> result = wxPay.microPay(data);
            logger.info(result.toString());
            if (result != null) {

                String return_code = result.get("return_code");

                logger.info(return_code);

                if (success.equals(return_code)) {
                    String result_code = result.get("result_code");
                    logger.info(result_code);
                    if (success.equals(result_code)) {
                        return true;
                    } else {
                        String err_code = result.get("err_code");
                        logger.info(err_code);
                        if ("USERPAYING".equals(err_code)) {
                            //用户输入密码中，每隔5秒查询状态

                            int count = 0;
                            boolean doWhile = false;

                            Map<String, String> orderQueryData = new HashMap<>();
                            orderQueryData.put("out_trade_no", orderNo);
                            orderQueryData.put("sub_mch_id", sub_mch_id);

                            logger.info(orderNo);

                            while(!doWhile) {
                                try {
                                    Thread.sleep(5 * 1000); //设置暂停的时间 5 秒
                                    count ++ ;
                                    logger.info(sdf.format(new Date()) + "--订单查询支付状态请求第" + count + "次");


//                                    Map<String, String> orderQueryResult = wxPay.orderQuery(orderQueryData);
                                    Map<String, String> orderQueryResult = wxPay.orderQuery(orderQueryData);

                                    System.out.println(JsonUtil.toJson(orderQueryResult));
                                    String order_return_code = orderQueryResult.get("return_code");

                                    if (success.equals(order_return_code)) {
                                        String order_result_code = orderQueryResult.get("result_code");
                                        logger.info("order_result_code : {}" , order_result_code);
                                        if (success.equals(order_result_code)) {
                                            logger.info("order_result_code : {}" , order_result_code);
                                            String trade_state = orderQueryResult.get("trade_state");
                                            if (success.equals(trade_state)) {
                                                return true;
                                            } else if (!"USERPAYING".equals(trade_state)) {
                                                return false;
                                            }
                                        }
                                    }

                                    if (count == 6) {
                                        doWhile = true;

                                        //撤销订单
                                        wxPay.reverse(orderQueryData);
                                        return false ;
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }

                        }
                    }

                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    public static Map<String, Object> getWuzhenpayToken(String deviceId){

        SortedMap<String, String> param = new TreeMap<>();
        param.put("client", client);
        param.put("timeStr", sdf2.format(new Date()));
        param.put("nonceStr", "12345678");
        param.put("deviceCode", deviceId);


        /**
         * 1.获取请求参数(排除sign)以ASCII排序
         * 2.参数用'&',"=",拼接.
         *  示例:key1=value1&key2=value2&key3=value3(最后一位没有'&')
         * 3.md5加密后的值作为sign传递
         */
        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        System.out.printf(sign.substring(0, sign.length() - 1));
        sign = MD5Util.MD5Lower32(sign.substring(0, sign.length() - 1));
        param.put("sign", sign);

        System.out.println(sign);
        System.out.println(sign);
        try {

            HttpPost httpPost = new HttpPost("http://cbpay.wuzhenpay.com/device/active");
//            HttpPost httpPost = new HttpPost("https://device.wuzhenpay.com/device/active");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if("200".equals(map.get("code"))){
                Map<String, Object> data = (Map<String, Object>)map.get("data");

                System.out.println(data.get("token"));
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }



    public static Map<String, Object> getWuzhenpayToken20(String deviceId){

        SortedMap<String, String> param = new TreeMap<>();
        param.put("client", client);
        param.put("appid", appid);
        param.put("code", deviceId);


        /**
         * ###接口签名方式
         * 1、将所有需要签名的参数键值以升序排序
         * 2、将参数以&连接 param1=111&id=222，末尾不带&,需要将所有的值进行URL编码字符串
         * 3、第二步做好后还需要在字符串最后连接一个参数appid=值(该值由管理员提供)
         * 4、将得到的字符串以md5加密
         * 其他：默认不参与签名参数 page/sign/token/limit
         */
        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        sign += "appid=" + appid;
        System.out.printf(sign);
        sign = MD5Util.MD5Lower32(sign);
        param.put("sign", sign);

        System.out.println(sign);
        try {

            HttpPost httpPost = new HttpPost("http://cbpay.wuzhenpay.com/storev3/?service=Login.activation");
//            HttpPost httpPost = new HttpPost("https://chuanbei-api.wuzhenpay.com/storev3/?service=Login.activation");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if((Integer)map.get("ret") == 200){
                Map<String, Object> data = (Map<String, Object>)map.get("data");

                System.out.println(data.get("token"));
                System.out.println(data.get("branch_id"));
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }


    public static Map<String, String> wuzhenpay(String authCode, Long totalFee, String deviceId){
        Map<String, String> result = new HashMap<>();
        Map<String, Object> data = getWuzhenpayToken(deviceId);
        String token = (String) data.get("token");
        String merchantId = (String) data.get("merchantId");
        SortedMap<String, String> param = new TreeMap<>();
        param.put("authCode", authCode);
        param.put("client", client);
        param.put("deviceCode", deviceId);
        param.put("merchantId", merchantId);
        param.put("nonceStr", deviceId);
        param.put("payMoney", totalFee.toString());
        param.put("timeStr", sdf2.format(new Date()));
        param.put("token", token);

        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        System.out.printf(sign.substring(0, sign.length() - 1));
        sign = MD5Util.MD5Lower32(sign.substring(0, sign.length() - 1));
        param.put("sign", sign);

        try {
            HttpPost httpPost = new HttpPost("http://cbpay.wuzhenpay.com/device/trade/pay");
//            HttpPost httpPost = new HttpPost("https://device.wuzhenpay.com/device/trade/pay");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if("200".equals(map.get("code"))){

                System.out.println(map.get("data"));

                Map<String, Object> dataMap = (Map<String, Object>)map.get("data");

                String status = dataMap.get("status").toString();

                String payNo = dataMap.get("payNo").toString();

                if (success.equals(status)) {
                    result.put("success", "true");
                    result.put("payNo", payNo);
                    return result;
                } else {
                    boolean doWhile = false;
                    int count = 1;
                    while(!doWhile) {
                        try {
                            Thread.sleep(5 * 1000); //设置暂停的时间 5 秒
                            System.out.println("--订单查询支付状态请求第" + count + "次");
                            count ++ ;


                            String payStatus = getOrderStatus(payNo, merchantId, deviceId, token);

                            if (success.equals(payStatus)) {
                                result.put("success", "true");
                                result.put("payNo", payNo);
                                return result;
                            } else if (!"PAYING".equals(payStatus)) {
                                result.put("success", "false");
                                return result;
                            }

                            if (count == 6) {
                                doWhile = true;

                                result.put("success", "false");
                                return result;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    result.put("success", "false");
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.put("success", "false");
        return result;
    }



    public static Map<String, String> wuzhenpay20(String authCode, Long totalFee, String deviceId){
        Map<String, String> result = new HashMap<>();
        Map<String, Object> data = getWuzhenpayToken20(deviceId);
        String token = (String) data.get("token");
        String branch_id =  data.get("branch_id") + "";
        SortedMap<String, String> param = new TreeMap<>();
        param.put("code", authCode);
        param.put("client", client);
        param.put("branch_id", branch_id);
        param.put("appid", appid);
        param.put("money", PriceUtil.changeF2Y(totalFee));
        param.put("token", token);

        /**
         * ###接口签名方式
         * 1、将所有需要签名的参数键值以升序排序
         * 2、将参数以&连接 param1=111&id=222，末尾不带&,需要将所有的值进行URL编码字符串
         * 3、第二步做好后还需要在字符串最后连接一个参数appid=值(该值由管理员提供)
         * 4、将得到的字符串以md5加密
         * 其他：默认不参与签名参数 page/sign/token/limit
         */
        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        sign += "appid=" + appid;
        System.out.printf(sign);
        sign = MD5Util.MD5Lower32(sign);
        param.put("sign", sign);

        System.out.println(sign);

        try {
            HttpPost httpPost = new HttpPost("https://chuanbei-api.wuzhenpay.com/storev3/?service=Micropay.Go");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if((Integer)map.get("ret") == 200){

                System.out.println(map.get("data"));

                Map<String, Object> dataMap = (Map<String, Object>)map.get("data");

                String payNo = dataMap.get("id").toString();
                String status = dataMap.get("status").toString();


                if ("3".equals(status) || "2".equals(status)) {
                    result.put("payNo", payNo);
                    result.put("success", "true");
                    return result;
                } else {
                    boolean doWhile = false;
                    int count = 1;
                    while(!doWhile) {
                        try {
                            Thread.sleep(5 * 1000); //设置暂停的时间 5 秒
                            count ++ ;
                            System.out.println("--订单查询支付状态请求第" + count + "次");


//                            String payStatus = getOrderStatus20(payNo, branch_id, deviceId, token);
                            Map<String, Object> statusMap = getOrderPayStatus20(payNo, branch_id, token);

                            String payStatus = statusMap.get("status").toString();

                            //状态,0已取消|1未付款|2已付款|3已完成|4已退款|5部分退款|6付款中|7支付异常
                            if ("3".equals(payStatus) || "2".equals(payStatus)) {
//                                payNo = statusMap.get("pay_no").toString();
                                result.put("success", "true");/**/
                                result.put("payNo", payNo);
                                return result;
                            } else if (!"6".equals(payStatus)) {
                                result.put("success", "false");
                                return result;
                            }

                            if (count == 6) {
                                doWhile = true;

                                result.put("success", "false");
                                return result;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    result.put("success", "false");
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.put("success", "false");
        return result;
    }



    public static Boolean refund(Long refundFee, String payNo, String deviceId){
        Map<String, Object> data = getWuzhenpayToken(deviceId);
        String token = (String) data.get("token");
        String merchantId = (String) data.get("merchantId");
        SortedMap<String, String> param = new TreeMap<>();
        param.put("client", client);
        param.put("deviceCode", deviceId);
        param.put("merchantId", merchantId);
        param.put("nonceStr", deviceId);
        param.put("payNo", payNo);
        param.put("refundFee", refundFee.toString());
        param.put("timeStr", sdf2.format(new Date()));
        param.put("token", token);

        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        System.out.printf(sign.substring(0, sign.length() - 1));
        sign = MD5Util.MD5Lower32(sign.substring(0, sign.length() - 1));
        param.put("sign", sign);

        try {
            HttpPost httpPost = new HttpPost("https://device.wuzhenpay.com/device/trade/refund");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if("200".equals(map.get("code"))){

                System.out.println(map.get("data"));

                Map<String, Object> dataMap = (Map<String, Object>)map.get("data");

                String status = dataMap.get("status").toString();

                if ("WAITING".equals(status) || success.equals(status)) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }



    public static Boolean refund20(Long refundFee, String payNo, String deviceId){
        Map<String, Object> data = getWuzhenpayToken20(deviceId);
        String token = (String) data.get("token");
        String branch_id = (String) data.get("branch_id");
        SortedMap<String, String> param = new TreeMap<>();
        param.put("client", client);
        param.put("branch_id", branch_id);
        param.put("id", payNo);
        param.put("appid", appid);
        param.put("refundFee", PriceUtil.changeF2Y(refundFee));
        param.put("token", token);

        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        System.out.printf(sign.substring(0, sign.length() - 1));
        sign = MD5Util.MD5Lower32(sign.substring(0, sign.length() - 1));
        param.put("sign", sign);

        try {
            HttpPost httpPost = new HttpPost("https://chuanbei-api.wuzhenpay.com/storev3/?service=Order.Refund");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if("200".equals(map.get("code"))){

                System.out.println(map.get("data"));

                Map<String, Object> dataMap = (Map<String, Object>)map.get("data");

                String status = dataMap.get("status").toString();

                if ("WAITING".equals(status) || success.equals(status)) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    public static String getOrderStatus(String payNo, String merchantId, String deviceId, String token){
        SortedMap<String, String> param = new TreeMap<>();
        param.put("client", client);
        param.put("deviceCode", deviceId);
        param.put("merchantId", merchantId);
        param.put("nonceStr", "12345678");
        param.put("payNo", payNo);
        param.put("timeStr", sdf2.format(new Date()));
        param.put("token", token);

        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        System.out.printf(sign.substring(0, sign.length() - 1));
        sign = MD5Util.MD5Lower32(sign.substring(0, sign.length() - 1));
        param.put("sign", sign);

        try {
            HttpPost httpPost = new HttpPost("https://device.wuzhenpay.com/device/trade/query");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if("200".equals(map.get("code"))){

                System.out.println(map.get("data"));

                Map<String, Object> dataMap = (Map<String, Object>)map.get("data");

                String status = dataMap.get("status").toString();

                return status;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String getOrderStatus20(String payNo, String branch_id, String deviceId, String token){
        SortedMap<String, String> param = new TreeMap<>();
        param.put("client", client);
        param.put("token", token);
        param.put("branch_id", branch_id);
        param.put("appid", appid);
        param.put("order_number", payNo);
        param.put("start_time", sdf2.format(new Date()));
        param.put("is_only", "true");

        /**
         * ###接口签名方式
         * 1、将所有需要签名的参数键值以升序排序
         * 2、将参数以&连接 param1=111&id=222，末尾不带&,需要将所有的值进行URL编码字符串
         * 3、第二步做好后还需要在字符串最后连接一个参数appid=值(该值由管理员提供)
         * 4、将得到的字符串以md5加密
         * 其他：默认不参与签名参数 page/sign/token/limit
         */
        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        sign += "appid=" + appid;
        System.out.printf(sign);
        sign = MD5Util.MD5Lower32(sign);
        param.put("sign", sign);

        System.out.println(sign);

        try {
            HttpPost httpPost = new HttpPost("https://chuanbei-api.wuzhenpay.com/storev3/?service=Order.FindOrder");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if((Integer)map.get("ret") == 200){

                System.out.println(map.get("data"));

                Map<String, Object> dataMap = (Map<String, Object>)map.get("data");

                String status = dataMap.get("status").toString();

                return status;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static Map<String, Object> getOrderPayStatus20(String id, String branch_id, String token){
        SortedMap<String, String> param = new TreeMap<>();
        param.put("client", client);
        param.put("token", token);
        param.put("branch_id", branch_id);
        param.put("appid", appid);
        param.put("id", id);

        /**
         * ###接口签名方式
         * 1、将所有需要签名的参数键值以升序排序
         * 2、将参数以&连接 param1=111&id=222，末尾不带&,需要将所有的值进行URL编码字符串
         * 3、第二步做好后还需要在字符串最后连接一个参数appid=值(该值由管理员提供)
         * 4、将得到的字符串以md5加密
         * 其他：默认不参与签名参数 page/sign/token/limit
         */
        String sign = "";
        for (Map.Entry<String, String> entry : param.entrySet()) {
            sign += entry.getKey() + "=" + entry.getValue() + "&";
        }

        sign += "appid=" + appid;
        System.out.printf(sign);
        sign = MD5Util.MD5Lower32(sign);
        param.put("sign", sign);

        System.out.println(sign);

        try {
            HttpPost httpPost = new HttpPost("https://chuanbei-api.wuzhenpay.com/storev3/?service=Micropay.Query");

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (Map.Entry<String, String> entry : param.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse closeableResponse = HttpConnectionManager.getHttpClient().execute(httpPost);
            String response = EntityUtils.toString(closeableResponse.getEntity());

            System.out.println("resp=" + response);

            System.out.printf(response);
            Map<String, Object> map = JsonUtil.parse(response, Map.class);

            if((Integer)map.get("ret") == 200){

                System.out.println(map.get("data"));

                Map<String, Object> dataMap = (Map<String, Object>)map.get("data");

                String status = dataMap.get("status").toString();

                return dataMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
/*
    public static void main(String[] args) {
        Map<String,String> m = WXServerPayService.wuzhenpay20("134508179161763606", 1l,"4C:ED:FB:C2:17:AC");

        System.out.println(m.get("success"));
    }*/
}
